# -*- encoding: utf-8 -*-


import time
import apolloCommon.mysqlPool as mysqlPool
from .common.constants import *


mysqlPool.InitDB(10)


class MySqlManager(object):
    @staticmethod
    def QueryPlayerHackerDeadline(uid, callback):
        # type: (int, callable) -> None
        def function(connection):
            cursor = connection.cursor()
            cursor.execute('SELECT `deadline` FROM `T312B2THacker` WHERE `uid` = %s', (uid, ))

            try:
                deadline = cursor.fetchone()[0]
                print "QueryPlayerHackerDeadline: %s" % deadline, type(deadline)
            except:
                deadline = -1

            return deadline

        mysqlPool.AsyncExecuteFunctionWithOrderKey(function, "{uid}-hacker".format(uid=uid), callback)

    @staticmethod
    def AddPlayerHackerTime(uid, addition):
        # type: (int, int) -> None
        if 0 <= addition < MAX_UNSIGNED_INT:
            def function(connection):
                cursor = connection.cursor()
                cursor.execute('SELECT `deadline` FROM `T312B2THacker` WHERE `uid` = %s', (uid, ))

                try:
                    deadline = cursor.fetchone()[0]
                    print "AddPlayerHackerTime: %s" % deadline, type(deadline)
                except:
                    deadline = -1

                current_time = int(time.time())
                if deadline != 0:
                    deadline = min(max(deadline, current_time) + addition, MAX_UNSIGNED_INT) if addition != 0 else 0
                    cursor.execute(
                        'INSERT INTO `T312B2THacker` (`uid`, `deadline`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE `deadline` = %s',
                        (uid, deadline, deadline)
                    )

            mysqlPool.AsyncExecuteFunctionWithOrderKey(function, "{uid}-hacker".format(uid=uid), None)



























